package com.ruoyi.web.controller.login;


import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.KaurConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.AESUtil;
import com.ruoyi.common.utils.CullenUtils;
import com.ruoyi.common.utils.OrderUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.module.po.PhonePo;
import com.ruoyi.module.po.ProfilePo;
import com.ruoyi.module.po.SendSmsRequest;
import com.ruoyi.module.po.SmsLoginRequest;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import com.ruoyi.thirdParty.service.ITencentCloudSmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 文件描述: 短信控制器
 *
 * @author Cullen
 */
@Anonymous
@RestController
@Api(tags = "腾讯云-短信处理")
@RequestMapping("/thirdParty/sms")
public class TencentCloudSmsController {

    @Autowired
    private ITencentCloudSmsService smsService;
    @Autowired
    private SysUserServiceImpl userService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private TokenService tokenService;


//    @PostMapping("/send")
//    @ApiOperation(value = "自定义发送短信")
//    public AjaxResult sendSms(@RequestBody SendSmsRequest request) {
//        smsService.sendSms(request);
//        return AjaxResult.success();
//    }


    @PostMapping("/smsLoginMsg")
    @ApiOperation(value = "获取登录短信验证码")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult smsLogin(@RequestBody PhonePo po) {
        if(StringUtils.isEmpty(po.getPhone())) {
            throw new ServiceException("请输入手机号...");
        }
        String decryptPhone;
        try {
            decryptPhone = AESUtil.decrypt(po.getPhone());
        } catch (Exception e) {
            throw new ServiceException("解密失败" + e.getMessage());
        }
        String randomNum = OrderUtils.getRandomNum(6);
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setTemplateId(1522419);
        sendSmsRequest.setValues(new String[]{randomNum, "30"});
        sendSmsRequest.setPhone(decryptPhone);
        smsService.sendSms(sendSmsRequest);
        redisCache.setCacheObject(po.getPhone(), randomNum, 30, TimeUnit.MINUTES);
        return AjaxResult.success();
    }

    @PostMapping("/smsLogin")
    @ApiOperation(value = "短信登录")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult smsLogin(@Validated @RequestBody SmsLoginRequest request) {
        String captcha = redisCache.getCacheObject(request.getPhone());
        CullenUtils.validateDataThrowException(StringUtils.isEmpty(captcha), "验证码已过期，请重新申请...");
        CullenUtils.validateDataThrowException(!captcha.equals(request.getCaptcha()), "验证失败，请核对验证码...");
        SysUser user = userService.selectUserByUserName(request.getPhone());
        if (request.getType().equals(Constants.APP)) {
            if (user == null) {
                SysUser sysUser = new SysUser();
                sysUser.setNickName("普通用户" + OrderUtils.getRandom(10L));
                sysUser.setUserName(request.getPhone());
                sysUser.setEmail("");
                sysUser.setPhonenumber(request.getPhone());
                sysUser.setSex("2");
                sysUser.setAvatar(KaurConstants.DEFAULT_AVATAR);
                sysUser.setPassword("");
                sysUser.setStatus("0");
                sysUser.setDelFlag("0");
                sysUser.setLoginDate(new Date());
                sysUser.setRoleIds(new Long[]{5L});
                userService.insertUser(sysUser);
                sysUser.setRoles(roleService.selectRolesByUserId(sysUser.getUserId()));
                LoginUser loginUser = new LoginUser();
                loginUser.setUser(sysUser);
                loginUser.setUserId(sysUser.getUserId());
                loginUser.setToken(tokenService.createToken(loginUser));
                return AjaxResult.success(loginUser);
            } else {
                CullenUtils.validateDataThrowException("1".equals(user.getStatus()), "账户已停用...");
                LoginUser loginUser = new LoginUser();
                user.setRoles(roleService.selectRolesByUserId(user.getUserId()));
                loginUser.setUser(user);
                loginUser.setUserId(user.getUserId());
                loginUser.setToken(tokenService.createToken(loginUser));
                String openIdApplet = request.getOpenIdApplet();
                if (openIdApplet != null) {
                    user.setOpenId(openIdApplet);
                    userService.updateUser(user);
                }
                String openSecond = request.getOpenSecond();
                if (openSecond != null) {
                    user.setOpenSecond(openSecond);
                    userService.updateUser(user);
                }
                return AjaxResult.success(loginUser);
            }
        } else if (request.getType().equals(Constants.PC)) {
            validateUser(user);
            CullenUtils.validateDataThrowException("普通用户".equals(user.getRoleName()), "未获得授权");
            LoginUser loginUser = new LoginUser();
            user.setRoles(roleService.selectRolesByUserId(user.getUserId()));
            loginUser.setUser(user);
            loginUser.setUserId(user.getUserId());
            loginUser.setToken(tokenService.createToken(loginUser));
            return AjaxResult.success(loginUser);
        } else {
            throw new ServiceException("未知登录设备...");
        }
    }

    @PostMapping("/retrievePasswordCaptcha")
    @ApiOperation(value = "获取找回密码短信验证码")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult retrievePasswordCaptcha(@RequestBody PhonePo po) {
        CullenUtils.validateDataThrowException(StringUtils.isEmpty(po.getPhone()), "请输入手机号...");
        String decryptPhone;
        try {
            decryptPhone = AESUtil.decrypt(po.getPhone());
        } catch (Exception e) {
            throw new ServiceException("解密失败" + e.getMessage());
        }
        String randomNum = OrderUtils.getRandomNum(6);
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setTemplateId(1522418);
        sendSmsRequest.setValues(new String[]{randomNum, "30"});
        sendSmsRequest.setPhone(decryptPhone);
        smsService.sendSms(sendSmsRequest);
        redisCache.setCacheObject(po.getPhone(), randomNum, 30, TimeUnit.MINUTES);
        return AjaxResult.success();
    }

    @PostMapping("/profileInfoCaptcha")
    @ApiOperation(value = "获取修改个人信息短信验证码")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult profileInfoCaptcha(@RequestBody PhonePo po) {
        CullenUtils.validateDataThrowException(StringUtils.isEmpty(po.getPhone()), "请输入手机号...");
        String decryptPhone;
        try {
            decryptPhone = AESUtil.decrypt(po.getPhone());
        } catch (Exception e) {
            throw new ServiceException("解密失败" + e.getMessage());
        }
        String randomNum = OrderUtils.getRandomNum(6);
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setTemplateId(1767137);
        sendSmsRequest.setValues(new String[]{randomNum, "30"});
        sendSmsRequest.setPhone(decryptPhone);
        smsService.sendSms(sendSmsRequest);
        redisCache.setCacheObject(po.getPhone(), randomNum, 30, TimeUnit.MINUTES);
        return AjaxResult.success();
    }

//    @PostMapping("/smsWithdrawal")
//    @ApiOperation(value = "发送提现短信验证码")
//    @Transactional(rollbackFor = Exception.class)
//    public AjaxResult smsWithdrawal(@RequestBody PhonePo po) {
//        CullenUtils.validateDataThrowException(StringUtils.isEmpty(po.getPhone()), "请输入手机号...");
//        String decryptPhone;
//        try {
//            decryptPhone = AESUtil.decrypt(po.getPhone());
//        } catch (Exception e) {
//            throw new ServiceException("解密失败" + e.getMessage());
//        }
//        String randomNum = OrderUtils.getRandomNum(6);
//        SendSmsRequest sendSmsRequest = new SendSmsRequest();
//        sendSmsRequest.setTemplateId(2006769);
//        sendSmsRequest.setValues(new String[]{randomNum, "5"});
//        sendSmsRequest.setPhone(decryptPhone);
//        smsService.sendSms(sendSmsRequest);
//        redisCache.setCacheObject(po.getPhone(), randomNum, 5, TimeUnit.MINUTES);
//        return AjaxResult.success();
//    }

    @ApiOperation("校验验证码")
    @Log(title = "校验验证码", businessType = BusinessType.OTHER)
    @PostMapping("/profileValidate")
    public AjaxResult profileValidate(@RequestBody ProfilePo po) {
        CullenUtils.validateDataThrowException(StringUtils.isEmpty(po.getPhone()), "请传入手机号...");
        String captcha = redisCache.getCacheObject(po.getPhone());
        CullenUtils.validateDataThrowException(StringUtils.isEmpty(captcha), "验证码已过期，请重新申请...");
        CullenUtils.validateDataThrowException(!captcha.equals(po.getCaptcha()), "验证失败，请核对验证码...");
        return AjaxResult.success();
    }

    /**
     * 空判
     *
     * @param user 用户
     */
    private void validateUser(SysUser user) {
        CullenUtils.validateDataThrowException(user == null, "没有该用户信息...");
    }
}
